package com.sky.controller.admin;

import com.github.pagehelper.Page;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@Api(tags = "菜品接口")
@RestController
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 获取菜品列表
    @ApiOperation("分页查询菜品")
    @GetMapping("/page")
    public Result<PageResult> getDishList(DishPageQueryDTO dishPageQueryDTO) {
        PageResult pageResult = dishService.getDishList(dishPageQueryDTO);

        return Result.success(pageResult);
    }

    // 新增菜品
    @ApiOperation("新增菜品")
    @PostMapping
    public Result<Object> addDish(@RequestBody DishDTO dishDTO) {
        dishService.insertDish(dishDTO);
        // 清空缓存
        redisTemplate.delete("dish_" + dishDTO.getCategoryId());

        return Result.success();
    }

    // 根据id获取菜品
    @ApiOperation("id获取菜品")
    @GetMapping("/{id}")
    public Result<DishVO> getDishById(@PathVariable Long id) {
        DishVO dish = dishService.getDishById(id);

        return Result.success(dish);
    }

    // 修改菜品
    @ApiOperation("修改菜品")
    @PutMapping
    public Result<Object> updateDish(@RequestBody DishDTO dishDTO) {
        dishService.updateDish(dishDTO);
        //清空缓存
        Set keys = redisTemplate.keys("*dish_*");
        redisTemplate.delete(keys);

        return Result.success();
    }

    // 批量删除菜品
    @ApiOperation("删除菜品")
    @DeleteMapping
    public Result<String> deleteDish(@RequestParam  List<Long> ids) {
        log.info("dishIdList：{}", ids);
        dishService.deleteDish(ids);
        // 清空缓冲
        Set keys = redisTemplate.keys("*dish_*");
        redisTemplate.delete(keys);

        return Result.success();
    }

    // 菜品启售/禁售
    @ApiOperation("菜品启售/禁售")
    @PostMapping("/status/{status}")
    public Result<String> changeStatus(@PathVariable Integer status,@RequestParam Long id) {
        dishService.changeStatus(status, id);
        // 清空缓冲
        Set keys = redisTemplate.keys("*dish_*");
        redisTemplate.delete(keys);

        return Result.success();
    }

    // 根据类型查询菜品
    @ApiOperation("类型查询菜品")
    @GetMapping("/list")
    public Result<List<Dish>> getDishByCategory(@RequestParam Long categoryId) {
        List<Dish> dishList = dishService.getDishByCategory(categoryId);

        return Result.success(dishList);
    }
}
